package br.com.nuccitec.jfera.remote {
	import br.com.nuccitec.jfera.event.RemoteEvent;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import mx.messaging.ChannelSet;
	import mx.messaging.channels.AMFChannel;
	import mx.messaging.channels.SecureAMFChannel;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	import spark.components.Application;

	public class RemoteHandler {
		public var destination:String;
		private var channelSet:ChannelSet;
		public var rootUI:Object;

		/**
		 * Put the root aplication UI
		 * */
		public function RemoteHandler(rootUI:IEventDispatcher,destination:String,channel:String) {
			this.rootUI=rootUI;
			rootUI.addEventListener(RemoteEvent.REMOTE_EVENT,remoteExecutionHandler);
			this.destination=destination;
			channelSet=new ChannelSet;
			channelSet.addChannel(new AMFChannel("granite-service",channel));
		}

		protected function remoteExecutionHandler(event:RemoteEvent):void {
			var request:RemoteRequest=new RemoteRequest(event.remoteId,event.objectVO);
			var remoteObject:RemoteObjectNucci=new RemoteObjectNucci(destination,event,rootUI);
			remoteObject.channelSet=channelSet;
			if(rootUI&&rootUI.hasOwnProperty("enabled")) {
				rootUI.enabled=false;
			}
			remoteObject.executeOnServer(request);
		}
	}
}